<template>
  <div id="home">
    <top-nav class="home_bgc">
      <div slot="center">购物街</div>
    </top-nav>
    <TabControl :titles="['流行', '新款', '精选']"
                class="tabControl"
                @tabClick="tabClick"
                ref="tabControl1"
                v-show="isTabFixed" />
    <scroll class="content"
            ref="scroll"
            :probe-type="3"
            @scroll="scrollDistance"
            :pull-up-load="true"
            @pullingUp="loadMore">
      <home-swiper :banners="banners" @swiperImgLoad="swiperImgLoad"/>
      <home-recommend :recommends="recommends"/>
      <week-fashion />
      <TabControl :titles="['流行', '新款', '精选']"
                  @tabClick="tabClick"
                  ref="tabControl2" />
      <ProductsList :products="showProducts"/>
    </scroll>

    <!--组件不能直接监听点击事件，要在事件后加入 .native-->
    <BackTop @click.native="BackTop" v-show="isShowBackTop"/>
  </div>
</template>

<script>
  import HomeSwiper from "./childComponents/HomeSwiper";
  import HomeRecommend from "./childComponents/HomeRecommend";
  import WeekFashion from "./childComponents/WeekFashion";

  import TopNav from "../../components/common/topnav/TopNav";
  import Scroll from "../../components/common/scroll/Scroll";
  import TabControl from "../../components/content/TabControl/TabControl";
  import ProductsList from "../../components/content/product/ProductsList";
  import BackTop from "../../components/content/backTop/BackTop";

  import {getHomeMultiData, getProducts} from "../../network/home";
  import {backTopMixin, itemImgListenerMixin} from "../../common/mixin";

  export default {
    name: "Home",
    components: {
      HomeSwiper,
      HomeRecommend,
      WeekFashion,
      TopNav,
      TabControl,
      ProductsList,
      Scroll,
      BackTop
    },
    //使用混入的方式将mounted中重复的代码封装
    mixins: [itemImgListenerMixin, backTopMixin],
    computed: {
      showProducts() {
        return this.products[this.currentType].list
      }
    },
    //创建data存储请求过来的数据
    data() {
      return {
        banners: [],
        recommends: [],
        products: {
          'pop': {page: 0, list: []},
          'new': {page: 0, list: []},
          'sell': {page: 0, list: []}
        },
        currentType: 'pop',
        tabConOffsetTop: 0,
        isTabFixed: false,
        saveY: 0
      }
    },
    activated() {
      this.$refs.scroll.scrollTo(0, this.saveY, 0)
      this.$refs.scroll.refresh()
    },
    deactivated() {
      //保存在首页的位置
      this.saveY = this.$refs.scroll.getScrollY()

      //取消全局事件的监听
      this.$bus.$off('itemImgLoad', this.itemImageListener)
    },
    //created中一般只写主要逻辑
    created() {
      //发送网络请求
      //1、请求多个数据
      this.getHomeData()
      //2、请求商品数据
      this.getProductsData('pop')
      this.getProductsData('new')
      this.getProductsData('sell')

      /*//在created里面通过document.querySelector()/this.$refs.**获取元素的时候都为空值（null）
      //3、监听ProListItem中图片加载完成的事件
      this.$bus.$on('itemImgLoad', () => {
        //因为是回调函数所以this.$refs.**的值不为空
        this.$refs.scroll.refresh()
      })*/
    },
    /*mounted() {
      //在created里面通过document.querySelector()/this.$refs.**获取元素的时候都为空值（null），所以要在mounted中做
      //3、监听ProListItem中图片加载完成的事件
      const refresh = this.debounce(this.$refs.scroll.refresh, 200)
      //对监听的事件进行保存
      this.itemImageListener = () => {
        refresh()
      }
      this.$bus.$on('itemImgLoad', this.itemImageListener)
    },*/
    methods: {
      /**
       * 网络请求相关的方法
       */
      getHomeData() {
        getHomeMultiData().then(res => {
          this.banners=res.data.banner.list;
          this.recommends=res.data.recommend.list;
          this.isChange=!this.isChange;
          this.$forceUpdate();
        })
      },
      getProductsData(type) {
        const page = this.products[type].page + 1
        getProducts(type, page).then(res => {
          //将结果根据类型保存到对应的list数组中
          this.products[type].list.push(...res.data.list)
          this.products[type].page += 1

          //当上拉加载完毕后，需要调用finishPullUp方法才能继续加载
          this.$refs.scroll.finishPullUp()
        })
      },

      /**
       * 时间监听相关的方法
       */
      tabClick(state) {
        switch (state) {
          case 0:
            this.currentType='pop'
            break
          case 1:
            this.currentType='new'
            break
          case 2:
            this.currentType='sell'
            break
        }
        this.$refs.tabControl1.recordState = state;
        this.$refs.tabControl2.recordState = state;
      },
      //判断滚动的位置
      scrollDistance(position) {
        // console.log(position);
        //1、根据滚动距离显示回到顶部按钮
        this.isShowBackTop=(-position.y)>=1200

        //2、根据滚动距离决定TabControl是否吸顶（position: fixed）
        this.isTabFixed = (-position.y)>this.tabConOffsetTop
      },
      //上拉加载更多
      loadMore() {
        //根据当前选中的状态决定哪个加载更多
        this.getProductsData(this.currentType)
      },
      //获取TabControl的offsetTop
      swiperImgLoad() {
        //所有组件都有一个属性$el ：用于获取组件中的元素
        // console.log(this.$refs.tabControl.$el.offsetTop);
        this.tabConOffsetTop = this.$refs.tabControl2.$el.offsetTop;
      }
    }
  }
</script>

<!--scoped：作用域-->
<style scoped>
  #home {
    /*padding-top: 44px;*/
    height: 100vh;/*vh表示视口单位*/
    position: relative;
  }
  .home_bgc {
    background-color: var(--color-tint);
    color: #fff;
    width: 100%;
    font-weight: 600;
    /*在使用浏览器原生滚动的时候使用，为了不让导航栏跟随一起滚动
    position: fixed;
    left: 0;
    top: 0;
    z-index: 20;*/
  }
  .tabControl {
    position: relative;
    z-index: 10;
  }

  /*.tabControl {
    position: sticky;!*根据top值来决定当前的position是sticky还是fixed，缺点是设置了这个属性的标签是透明的*!
    top: 44px;
    z-index: 10;
  }*/

  /*确定content区域的高度*/
  /*第一种方法*/
  /*.content {
    height: calc(100% - 93px);
    overflow: hidden;
    margin-top: 44px;
  }*/
  /*第二种方法*/
  .content {
    position: absolute;
    top: 44px;
    bottom: 49px;
    left: 0;
    right: 0;
    overflow: hidden;
  }
</style>

